package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.WorkContactRoomEntity;
import com.pactera.madp.cp.api.model.transfer.GetContactRoom;
import com.pactera.madp.cp.api.dto.workroom.WorkContactRoomIndexDto;
import com.pactera.madp.cp.mapper.WorkContactRoomMapper;
import com.pactera.madp.cp.service.IWorkContactRoomService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WorkContactRoomServiceImpl extends ServiceImpl<WorkContactRoomMapper, WorkContactRoomEntity> implements IWorkContactRoomService {

    @Resource
    private WorkContactRoomMapper workContactRoomMapper;

    @Override
    public List<GetContactRoom> GetContactRoomArray(List<String> roomIds, List<Integer> contactIds) {
        return this.baseMapper.getContactRoomList(contactIds, roomIds);
    }


    /**
     * @description:通过客户群id获得信息
     * @return:
     * @author: Huayu
     * @time: 2020/12/11 9:43
     */
    @Override
    public List<WorkContactRoomEntity> getWorkContactRoomsByRoomId(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("room_id", id);
        return this.workContactRoomMapper.getWorkContactRoomsByRoomId(map);
    }

    /**
     * @description 获取当前群人数
     * @author zhaojinjian
     * @createTime 2020/12/14 16:00
     */
    @Override
    public Map<Integer, Long> getContactRoomSum(List<Integer> roomIds) {
        QueryWrapper<WorkContactRoomEntity> contactRoomWrapper = new QueryWrapper<>();
        contactRoomWrapper.eq("status", 1);
        contactRoomWrapper.in("room_id", roomIds);
        List<WorkContactRoomEntity> contactRoomList = this.list(contactRoomWrapper);
        if (contactRoomList != null) {
            return contactRoomList.stream().collect(Collectors.groupingBy(WorkContactRoomEntity::getRoomId, Collectors.counting()));
        }
        return null;
    }


    /**
     * @description:通过条件获得成员基础信息
     * @return:
     * @author: Huayu
     * @time: 2020/12/11 9:43
     */
    @Override
    public List<WorkContactRoomEntity> getWorkContactRoomIndex(WorkContactRoomIndexDto workContactRoomIndexDto, String workEmployeeIds, String workContactIds) {
        String clStr = "wxUserId,contact_id,contact_id,employee_id,unionid,room_id,join_scene,type,status,join_time,out_time";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roomId", workContactRoomIndexDto.getWorkRoomId());
        map.put("status", workContactRoomIndexDto.getStatus());
        map.put("joinTimeStart", workContactRoomIndexDto.getStartTime());
        map.put("joinTimeEnd", workContactRoomIndexDto.getEndTime());
        map.put("workEmployeeIds", workEmployeeIds.split(","));
        map.put("workContactIds", workContactIds);
        List<WorkContactRoomEntity> workContactRoomList = workContactRoomMapper.getWorkContactRoomIndex(map);
        return workContactRoomList;
    }

    /**
     * @description:根据条件检索成员所在群的信息
     * @return:
     * @author: Huayu
     * @time: 2020/12/17 14:13
     */
    @Override
    public List<WorkContactRoomEntity> getWorkContactRoomsByWxUserId(String wxUserId, String room_id) {
        QueryWrapper<WorkContactRoomEntity> workContactRoomQueryWrapper = new QueryWrapper<WorkContactRoomEntity>();
        workContactRoomQueryWrapper.select(room_id);
        workContactRoomQueryWrapper.eq("wx_user_id", wxUserId);
        return this.baseMapper.selectList(workContactRoomQueryWrapper);
    }

    @Override
    public List<WorkContactRoomEntity> getIdByRoomIdAndWxUserId(Integer id, String wxUserId) {
        QueryWrapper<WorkContactRoomEntity> workContactRoomQueryWrapper = new QueryWrapper<WorkContactRoomEntity>();
        workContactRoomQueryWrapper.select("id");
        workContactRoomQueryWrapper.eq("wx_user_id", wxUserId);
        workContactRoomQueryWrapper.eq("room_id", id);
        return this.baseMapper.selectList(workContactRoomQueryWrapper);
    }

    @Override
    public Integer createWorkContactRoom(WorkContactRoomEntity workContactRoomEntity) {
        return this.baseMapper.insert(workContactRoomEntity);
    }

    @Override
    public boolean batchUpdateByIds(List<WorkContactRoomEntity> workContactRoomEntityUpdateList) {
        return this.updateBatchById(workContactRoomEntityUpdateList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateWorkContactRoomByIds(String deleteContactRoomIdArr, long time, Integer status) {
        String[] str = deleteContactRoomIdArr.split(",");
        Integer i = 0;
        for (String id : str) {
            WorkContactRoomEntity workContactRoomEntity = new WorkContactRoomEntity();
            workContactRoomEntity.setId(Integer.valueOf(id));
            workContactRoomEntity.setOutTime(DateTime.of(time).toString());
            workContactRoomEntity.setStatus(2);
            i = workContactRoomMapper.updateWorkContactRoomByIds(workContactRoomEntity);
        }
        return i;
    }

    @Override
    public List<WorkContactRoomEntity> getWorkContactRoomsInfoByRoomId(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("room_id", id);
        return this.workContactRoomMapper.getWorkContactRoomsByRoomId(map);
    }

    @Override
    public List<WorkContactRoomEntity> countWorkEmployeesByRoomIds(String roomIds) {
        QueryWrapper<WorkContactRoomEntity> workContactRoomQueryWrapper = new QueryWrapper<WorkContactRoomEntity>();
        workContactRoomQueryWrapper.in("room_id", roomIds);
        return this.baseMapper.selectList(workContactRoomQueryWrapper);
    }

    @Override
    public List<WorkContactRoomEntity> countAddWorkContactRoomsByRoomIdTime(String roomIds, Date startTime, Date endTime) {
        QueryWrapper<WorkContactRoomEntity> workContactRoomQueryWrapper = new QueryWrapper<WorkContactRoomEntity>();
        workContactRoomQueryWrapper.in("room_id", roomIds);
        workContactRoomQueryWrapper.ge("join_time", startTime);
        workContactRoomQueryWrapper.lt("join_time", endTime);
        return this.baseMapper.selectList(workContactRoomQueryWrapper);
    }

    @Override
    public List<WorkContactRoomEntity> countQuitWorkContactRoomsByRoomIdTime(String roomIds, Date startTime, Date endTime) {
        QueryWrapper<WorkContactRoomEntity> workContactRoomQueryWrapper = new QueryWrapper<WorkContactRoomEntity>();
        workContactRoomQueryWrapper.in("room_id", roomIds);
        workContactRoomQueryWrapper.ge("out_time", startTime);
        workContactRoomQueryWrapper.lt("out_time", endTime);
        return this.baseMapper.selectList(workContactRoomQueryWrapper);
    }

    @Override
    public Integer selectByRoomIds(List<Integer> roomIds) {
        return workContactRoomMapper.selectByRoomIds(roomIds);
    }

    @Override
    public Integer getStatistic(LocalDate plusDays, List<Object> roomIds) {
        return baseMapper.getStatistic(plusDays.toString(), roomIds);
    }

    /*@Override
    public WorkContactRoomDailyResp group(String end) {
        Integer corpId = CorpContextHolder.getCorpId();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<WorkRoomEntity> list = workRoomService.lambdaQuery()
                .eq(WorkRoomEntity::getCorpId, corpId)
                .list();
        List<WorkContactRoomEntity> workContactRoomEntities = null;
        HashMap<String, Object> map = formData(end, new WorkContactRoomDailyResp());
        workContactRoomEntities = formData();
        WorkContactRoomDailyResp workContactRoomDailyResp = new WorkContactRoomDailyResp();
        ArrayList<WorkContactRoomDailyIndexResp> workContactRoomDailyIndexResps = new ArrayList<>();
        //前一天的客户数
        Integer lastTotalContact = 0;
        //保存前一天的群数
        Object[] keys =  map.keySet().toArray();
        Arrays.sort(keys);
        for (Object key : keys) {
            WorkContactRoomDailyIndexResp workContactRoomDailyIndexResp = new WorkContactRoomDailyIndexResp();
            //客群新增
            Integer roomAddNum = 0;
            //客群总数
            Integer roomTotal = 0;
            //客户新增
            Integer realAddContact = 0;
            //客户总数
            Integer totalContact = 0;
            //客户变化数
            Integer changeContact = 0;
            for (int i = 0; i < list.size(); i++) {
                WorkRoomEntity workRoomEntity = list.get(i);
                if (key.equals(workRoomEntity.getCreateTime().toLocalDate().toString())) roomAddNum++;
                String createTime = workRoomEntity.getCreateTime().toLocalDate().toString();
                if (createTime.compareTo((String) key) <= 0) roomTotal++;

            }
            for (int i = 0; i < workContactRoomEntities.size(); i++) {
                WorkContactRoomEntity workContactRoomEntity = workContactRoomEntities.get(i);
                String joinTime = sdf.format(workContactRoomEntity.getJoinTime());
                if (!workContactRoomEntity.getOutTime().trim().equals("") ) {
                    String outTime = sdf.format(workContactRoomEntity.getOutTime());
                    if (outTime.compareTo((String) key) >= 0) totalContact--;
                }

                if (key.equals(joinTime)) realAddContact++;

                if (joinTime.compareTo((String) key) <= 0) totalContact++;


            }
            changeContact = totalContact - lastTotalContact;
            lastTotalContact = totalContact;
            workContactRoomDailyIndexResp.setTime((String) key);
            workContactRoomDailyIndexResp.setContactRealAddNum(realAddContact);
            workContactRoomDailyIndexResp.setRoomTotal(roomTotal);
            workContactRoomDailyIndexResp.setRoomAddNum(roomAddNum);
            workContactRoomDailyIndexResp.setContactTotal(totalContact);
            workContactRoomDailyIndexResp.setContactAddNum(changeContact);
            workContactRoomDailyIndexResps.add(workContactRoomDailyIndexResp);
        }
        List<WorkContactRoomDailyIndexResp> newSortList = workContactRoomDailyIndexResps.stream().sorted(Comparator.comparing(WorkContactRoomDailyIndexResp::getTime).reversed())
                .collect(Collectors.toList());
        newSortList.remove(7);
        WorkContactRoomDailyIndexResp workContactRoomDailyIndexResp = newSortList.get(0);
        workContactRoomDailyResp.setRoomTotal(workContactRoomDailyIndexResp.getRoomTotal());
        workContactRoomDailyResp.setRoomAddNum(workContactRoomDailyIndexResp.getRoomAddNum());
        workContactRoomDailyResp.setContactTotal(workContactRoomDailyIndexResp.getContactTotal());
        workContactRoomDailyResp.setContactRealAddNum(workContactRoomDailyIndexResp.getContactRealAddNum());
        workContactRoomDailyResp.setContactAddNum(workContactRoomDailyIndexResp.getContactAddNum());
        workContactRoomDailyResp.setList(newSortList);
        return workContactRoomDailyResp;
    }
    private HashMap<String, Object> formData(String end, Object obj) {

        if (obj instanceof WorkContactDailyResp) {
            obj = new WorkContactDailyResp();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar date = Calendar.getInstance();
        Map<String, Object> map = new HashMap<String, Object>();

        if (end != null) {//按天统计
            try {
                date.setTime(sdf.parse(end));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            date.add(Calendar.DAY_OF_YEAR, -1);
            for (int i = 1; i <= 8; i++) {
                map.put(sdf.format(date.getTime()), obj);
                date.add(Calendar.DAY_OF_YEAR, -1);
            }
        } else {
            date.setTime(new Date());
            date.add(Calendar.DAY_OF_YEAR, -1);
            date.set(Calendar.HOUR_OF_DAY, 0);
            date.set(Calendar.MINUTE, 0);
            date.set(Calendar.SECOND, 0);
            date.set(Calendar.MILLISECOND, 0);
            for (int i = 1; i <= 8; i++) {
                map.put(sdf.format(date.getTime()), obj);
                date.add(Calendar.DAY_OF_YEAR, -1);
            }
        }
        return (HashMap<String, Object>) map;
    }


    private List<WorkContactRoomEntity> formData() {
        //获取客群的ids
        LambdaQueryWrapper<WorkRoomEntity> wrapperRoom = new LambdaQueryWrapper<>();
        wrapperRoom.select(WorkRoomEntity::getId);
        List<Long> roomIds = workRoomMapper.selectObjs(wrapperRoom).stream()
                .map(o -> (Long) o)
                .collect(Collectors.toList());
        //根据ids查询 workcontactroom数据表中的客户list
        List<WorkContactRoomEntity> list = this.lambdaQuery().
                eq(WorkContactRoomEntity::getEmployeeId, 0)
                .in(WorkContactRoomEntity::getRoomId, roomIds)
                .list();
        return list;
    }*/
}
